Golang : Set or add headers for many or different handlers
Problem :
In Golang, setting headers can be done easily with the Set() method.
At the moment, you are setting headers for each individual handler in such as manner :
func handlerA(w http.ResponseWriter, req *http.Request) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Set header for handler A."))
}
func handlerB(w http.ResponseWriter, req *http.Request) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Set header for handler B."))
}
Instead of setting header for each individual handler manually, you want to use a function to set the headers.
NOTE : This method can apply to Add headers as well
Solution :
Create a common SetHeaders()
function that will write to http.ResponseWriter. For example :
func SetHeaders(w http.ResponseWriter) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Content-Type", "text/plain")
}
func handlerA(w http.ResponseWriter, req *http.Request) {
SetHeaders(w)
w.Write([]byte("Set header for handler A."))
}
func handlerB(w http.ResponseWriter, req *http.Request) {
SetHeaders(w)
w.Write([]byte("Set header for handler B."))
}
See also : Golang : How to Set or Add Header http.ResponseWriter?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.7k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+20.6k Golang : Create and resolve(read) symbolic links
+13.8k Golang : How to convert a number to words
+17.6k Golang : Check if a directory exist or not
+6.4k Golang : Muxing with Martini example
+12.2k Golang : Listen and Serve on sub domain example
+12.8k Android Studio : Password input and reveal password example
+25.6k Mac/Linux and Golang : Fix bind: address already in use error
+4.6k Google : Block or disable caching of your website content
+6.8k Golang : How to fix html/template : "somefile" is undefined error?
+7.6k Golang : Get all countries phone codes
+11.6k Golang : How to parse plain email text and process email header?